package com.letv.app.ljodfh.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutCompat;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsoluteLayout;
import android.widget.CompoundButton;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.google.gson.Gson;
import com.jiongbull.jlog.JLog;
import com.letv.app.ljodfh.beans.LiveInfo;
import com.letv.app.ljodfh.beans.NewsClickBean;
import com.letv.app.ljodfh.beans.SingleResult;
import com.letv.app.ljodfh.ui.utils.UIUtils;
import com.letv.app.ljodfh.utils.UserManager;
import com.mob.tools.utils.DeviceHelper;
import com.rhang.LogCollector.RHLogger;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.ui.util.CustomFragmentChangeHelper;
import com.ruihang.generalibrary.ui.util.ViewUtils;
import com.ruihang.generalibrary.ui.widget.CustomCheckBox;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.ui.widget.CustomFrameLayout;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.DensityUtil;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.letv.app.ljodfh.R;
import com.letv.app.ljodfh.base.BaseActivity;
import com.letv.app.ljodfh.base.BaseCanPlayActivity;
import com.letv.app.ljodfh.base.Constances;
import com.letv.app.ljodfh.beans.ChatItem;
import com.letv.app.ljodfh.beans.FLive;
import com.letv.app.ljodfh.beans.FLiveDy;
import com.letv.app.ljodfh.http.AbsNetCallBack;
import com.letv.app.ljodfh.http.NetUtils;
import com.letv.app.ljodfh.push.IMsgRecieve;
import com.letv.app.ljodfh.push.MyJPushReceiver;
import com.letv.app.ljodfh.ui.adapter.holder.LiveRoomDynamicHolder;
import com.letv.app.ljodfh.ui.fragment.ChatRoomFragment;
import com.letv.app.ljodfh.ui.fragment.LiveRoomFragment;
import com.letv.app.ljodfh.ui.fragment.LivingChildFragment;
import com.letv.app.ljodfh.ui.utils.BarrageScreenController;
import com.letv.app.ljodfh.ui.utils.GlideUtil;
import com.letv.app.ljodfh.ui.utils.IBarrageControll;
import com.letv.app.ljodfh.ui.utils.SkipUtil;
import com.letv.app.ljodfh.ui.widget.BarragePlayerView;
import com.letv.app.ljodfh.ui.widget.BasePlayerView;
import com.letv.app.ljodfh.utils.ListTypeUtils;
import com.letv.app.ljodfh.utils.ResultAsyncTask;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import org.json.JSONArray;
import org.json.JSONObject;

import java.sql.Date;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

public class LivingActivity extends BaseCanPlayActivity implements CanRefreshLayout.OnLoadMoreListener
        , CanRefreshLayout.OnRefreshListener, CanRefreshLayout.IScrollView, IBarrageControll
        , LivingChildFragment.OnNetCallback, LiveRoomDynamicHolder.OnImageClickListener, IMsgRecieve {
    @BindView(R.id.living_refresh)
    protected CanRefreshLayout mRefreshLayout;
    @BindView(R.id.can_content_view)
    protected CustomFrameLayout container;
    @BindView(R.id.living_lay_tab)
    protected ViewGroup layTab;
    @BindView(R.id.living_lay_intro)
    protected ViewGroup layIntro;
    @BindView(R.id.title_top_layout)
    protected ViewGroup layTitle;
    @BindView(R.id.living_ac_base)
    protected ViewGroup baseLay;
    @BindView(R.id.living_img_video)
    protected CustomEXImageView topImg;
    @BindView(R.id.living_tx_intro)
    protected CustomFontTextView intro;
    @BindView(R.id.living_sec_date)
    protected CustomFontTextView date;
    @BindView(R.id.living_sec_source)
    protected CustomFontTextView liveSource;
    @BindView(R.id.living_tab_room_living)
    protected CustomFontTextView tabLive;
    @BindView(R.id.living_tab_room_chat)
    protected CustomFontTextView tabChat;
    @BindView(R.id.living_top_mode)
    protected CustomFontTextView livtTag;
    @BindView(R.id.living_sec_toggle)
    protected CustomCheckBox introToggle;
    @BindView(R.id.living_scroll_child)
    protected LinearLayoutCompat linear;
    @BindView(R.id.living_video_container)
    protected AbsoluteLayout videoContainer;
    @BindView(R.id.living_count)
    CustomFontTextView mLiveCountText;

    private LiveRoomFragment liveRoomFragment;
    private ChatRoomFragment chatRoomFragment;
    private CustomFragmentChangeHelper<LivingChildFragment> fragmentChangeHelper;

    private Handler handler;

    private boolean hasSelectRoom;
    /**
     * 是否是直播,此属性暂时只在设置测试数据是使用
     */
    private boolean isTempLiving;
    private boolean isFirst = true;
    private boolean isStart = false;
    private boolean isComplement = false;
    private BarrageScreenController screenController;

    private BarrageTestAsync barrageTestAsync;
    private FLive mFLive;
    private boolean mIsLoading = false;
    private String mUrl;
    private String liveUrl;
    private int mSelectedIndex = 0;

    private String topImgUrl;

    private boolean isFirstPlay = true;

    private boolean isPlayFromRoom;

    private int verOffset;
    /**
     * 聊天室视频播放的时长记录
     */
    private int roomPlayedPos;

    private Gson gson;

    private BarragePlayerView videoPlayer;

    private FLiveDy otherVideoTemp;

    private int mainVideoPos;

    private boolean isPlayingWhenPause;
    private boolean isFromACResult;//是否是从指定的activity返回的

    private ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        private int[] ii = new int[2];

        private int oldY;
        int c;

        @Override
        public void onGlobalLayout() {
            container.getLocationInWindow(ii);
            if (isPlayFromRoom && floatVideoUtils.isShowing()) {
                c = ii[1] - oldY;
                if (c != 0) {
                    ViewGroup.LayoutParams lp = videoContainer.getLayoutParams();
                    lp.height -= c;
                    videoContainer.setLayoutParams(lp);
                }
            }
            oldY = ii[1];
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUrl = getIntent().getStringExtra(BaseActivity.EX_URL);
        topImgUrl = getIntent().getStringExtra(BaseActivity.EX_DATA);
        isVideoTop = false;
        if (TextUtils.isEmpty(mUrl)) {
            toast(R.string.loading_invalid_data);
            finish();
            return;
        }

        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                msgHandler(msg);
            }
        };

        isTempLiving = getIntent().getBooleanExtra("liveTest", false);
        fragmentChangeHelper = new CustomFragmentChangeHelper<>(R.id.can_content_view);
        layTab.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (layTab.getHeight() > 0) {
//                    if (hasSelectRoom) {
//                        ViewGroup.LayoutParams lp = appBarLayout.getLayoutParams();
//                        lp.height = layTab.getHeight();
//                        appBarLayout.setLayoutParams(lp);
                    layTab.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//                    } else {
//                        selectTab(tabLive, tabChat);
//                    }
//                    tabLive.callOnClick();
                }
            }
        });
        GlideUtil.loadImgLarge169Def(this, topImgUrl, topImg);
//        if (!TextUtils.isEmpty(topImgUrl)) {
//        }
        container.getViewTreeObserver().addOnGlobalLayoutListener(globalLayoutListener);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRefreshLayout.setOnRefreshListener(this);
        container.setiScrollView(this);
        mRefreshLayout.autoRefresh();

//        getData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isFromACResult && isPlayingWhenPause) {
            if (floatVideoUtils != null) {
                if (floatVideoUtils.isShowing()) {
                    if (mainVideoPos > 0) {
                        floatVideoUtils.getPlayerView().setPlayPosition(mainVideoPos);
                    }
                    if (NetModeUtil.GetNetype(this) == 1) {
                        floatVideoUtils.startPlay();
                    }
                }
            }
        }
    }

    @Override
    protected void onPause() {
        isPlayingWhenPause = floatVideoUtils != null && floatVideoUtils.isPlaying();
        if (isPlayingWhenPause) {
            mainVideoPos = floatVideoUtils.getPlayerView().getCurrentPositionWhenPlaying();
        }
        super.onPause();
    }

    /********************后台心跳统计**********************/
    Handler handler1 = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null && msg.what == 111) {
                sendMsg();
            }
        }
    };
    private Timer readyTimer;
    private TimerTask RHTask;

    /**
     * 启动直播统计心跳
     */
    public void startAdService(final Handler mHandler) {
        if (null != mFLive && null != mFLive.getLiveInfo()) {
            long HeartbeatTime = 60 * 1000;//心跳时间
            try {
                readyTimer = new Timer(true);
                java.util.Date d1 = new java.util.Date();
                if (null == RHTask) {
                    RHTask = new TimerTask() {
                        @Override
                        public void run() {
                            Message msg = new Message();
                            msg.what = 111;
                            mHandler.sendMessage(msg);
                        }
                    };
                }
                readyTimer.schedule(RHTask, d1, HeartbeatTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void sendMsg() {
        if (null != mFLive && null != mFLive.getLiveInfo()) {
            JLog.e("RHLogger------", "liveHeartBeat");
            RHLogger.getInstance().liveHeartBeat(mFLive.getLiveInfo().getLiveId());
        }
    }

    /******************************************************/
    @Override
    protected void initInject() {
        setContentView(R.layout.activity_living);
        ButterKnife.bind(this);
    }


    @OnClick(value = {R.id.title_top_layout_edit, R.id.title_top_layout_back})
    public void shareClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_layout_edit:
                if (mFLive.getLiveInfo() != null && !TextUtils.isEmpty(mFLive.getLiveInfo().getSharedUrl())) {
                    LiveInfo info = mFLive.getLiveInfo();
                    info.setShareImage(topImgUrl);
                    setNewsId(info.getLiveId());
                    showShareFragment(mFLive.getLiveInfo(), new ShareFragment.OnShareFragmentClickListener() {
                        @Override
                        public void onClick(Pair<String, String> pair) {

                        }
                    });                } else {
                    toast(R.string.share_data_wrong);
                }
                break;
            case R.id.title_top_layout_back:
                finish();
                break;
        }

    }

    /**
     * 增加点击
     */
    private void initViewClickData(final String liveID) {
        ArrayMap<String, Object> p = new ArrayMap<>();
        p.put("id", liveID);
        p.put("type", 1);//type（0.新闻 1.直播)
        p.put("clientId", DeviceHelper.getInstance(this).getDeviceId());//clientId设备id
        NetUtils.getNetAdapter().addNewOrLivingClick(getOwnerName(), p, new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult vo) {
                JLog.e("", "" + vo.isSuccess());
            }

            @Override
            public void onEnd() {
                super.onEnd();
                //增加点击量完成之后，获取点击量
//                getLiveClickCount(liveID);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });


    }

    @Override
    protected void onDestroy() {
        if (null != RHTask) {
            RHTask.cancel();
            RHTask = null;
        }
        if (null != readyTimer) {
            readyTimer.cancel();
            readyTimer.purge();
            readyTimer = null;
        }

        if (null != mFLive && null != mFLive.getLiveInfo()) {
            RHLogger.getInstance().endLive(mFLive.getLiveInfo().getLiveId());
        }
        MyJPushReceiver.setMsgRecieve(null);
        if (container != null) {
            container.setiScrollView(null);
            container.getViewTreeObserver().removeOnGlobalLayoutListener(globalLayoutListener);
        }
        if (mRefreshLayout != null) {
            mRefreshLayout.setOnLoadMoreListener(null);
            mRefreshLayout.setOnRefreshListener(null);
        }
        if (barrageTestAsync != null) {
            barrageTestAsync.stop();
        }
        if (mFLive != null) {
            if (mFLive.getLiveInfo() != null) {
                deltJpushTag(mFLive.getLiveInfo().getLiveId());
            }
        }


        if (null != mFLive && null != mFLive.getLiveInfo() && mFLive.getLiveInfo().isLiving()) {
            handler.removeCallbacks(runnable);
        }
        if(null !=mFLive) {
            if (UserManager.isLoginS()) {
                StatisticsMainInit.newsInfoVisit(UserManager.getInstance().getUser().getPhoneNumber(), mFLive.getLiveInfo().getLiveId(),
                        mFLive.getLiveInfo().getLiveTitle(), "", "1");
            } else {
                StatisticsMainInit.newsInfoVisit("", mFLive.getLiveInfo().getLiveId(),
                        mFLive.getLiveInfo().getLiveTitle(), "", "1");
            }
        }





        super.onDestroy();
    }

    @Override
    protected void onCommentSendSuc(int mode) {
        super.onCommentSendSuc(mode);
    }

    @Override
    protected void onLoginSuc() {
        super.onLoginSuc();
        if (loginMode == Constances.MODE_COMMENT_SEND_COMMENT || loginMode == Constances.MODE_COMMENT_SEND_NEWS) {
            if (commentDiaFragment != null && commentDiaFragment.isResumed()) {
                commentDiaFragment.onLoginSuc();
            }
        }
    }

    @NonNull
    @Override
    protected BasePlayerView createdPlayerView() {
        if (videoPlayer == null) {
            videoPlayer = new BarragePlayerView(this);
            videoPlayer.setLiving(true);


            if (null != mFLive && null != mFLive.getLiveInfo()) {
                if (mFLive.getLiveInfo().isLiving()) {
                    handler.postDelayed(runnable, 0);
                } else {
                    videoPlayer.setOnPlayerStatusListener(new BasePlayerView.OnPlayerStatusChanged() {
                        @Override
                        public void OnPlaying() {
                            if (!isStart) {
                                if (UserManager.isLoginS()) {
                                    StatisticsMainInit.newsVideoPlay(UserManager.getInstance().getUser().getPhoneNumber(), mFLive.getLiveInfo().getLiveId(),
                                            mFLive.getLiveInfo().getLiveTitle(), videoPlayer.getDurationSecond(), 0);
                                } else {
                                    StatisticsMainInit.newsVideoPlay("", mFLive.getLiveInfo().getLiveId(),
                                            mFLive.getLiveInfo().getLiveTitle(), videoPlayer.getDurationSecond(), 0);
                                }
                            }
                            isStart = true;
                        }

                        @Override
                        public void OnError() {
                            JLog.e("OnPlayerStatusListener", "----OnError");
                        }

                        @Override
                        public void OnStop() {
                            JLog.e("OnPlayerStatusListener", "----OnStop");
                        }

                        @Override
                        public void OnEnd() {
                            JLog.e("OnPlayerStatusListener", "----OnEnd");
                            if (!isComplement) {
                                if (UserManager.isLoginS()) {
                                    StatisticsMainInit.newsVideoPlay(UserManager.getInstance().getUser().getPhoneNumber(), mFLive.getLiveInfo().getLiveId(),
                                            mFLive.getLiveInfo().getLiveTitle(), videoPlayer.getDurationSecond(), 1);
                                } else {
                                    StatisticsMainInit.newsVideoPlay("", mFLive.getLiveInfo().getLiveId(),
                                            mFLive.getLiveInfo().getLiveTitle(), videoPlayer.getDurationSecond(), 1);
                                }
                            }
                            isComplement = true;
                        }
                    });
                }
            }



        }




        return videoPlayer;
    }

    @Override
    public StandardGSYVideoPlayer getVideoPlayer() {
        return videoPlayer;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        JLog.e("bbab  request="+requestCode+"   result="+resultCode+"   data="+data+"  "+otherVideoTemp);
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SkipUtil.REQUEST_CODE_PLAY_BASE) {
            isFromACResult = true;
            if (otherVideoTemp == null || data == null) {
                return;
            }
            if (resultCode == RESULT_OK) {
                otherVideoTemp.setPlayedPos(0);
            } else {
                int pos = data.getIntExtra(SkipUtil.EX_POS, 0);
//                JLog.e("bbab result pos="+pos);
                otherVideoTemp.setPlayedPos(pos);
            }
        }
    }

    @Override
    public void onLoadMore() {
        mIsLoading = true;

        if (mSelectedIndex == 0) {
            if (liveRoomFragment != null) {
                liveRoomFragment.onLoadMore();
            }
        } else if (mSelectedIndex == 1) {
            if (chatRoomFragment != null) {
                chatRoomFragment.onLoadMore();
            }

        }
        //  }
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }

        JLog.e("zzaz ok  live=" + mFLive + "   select index=" + mSelectedIndex);
        mIsLoading = true;
        if (mFLive == null || mFLive.getLiveInfo() == null) {
            getData();
            return;
        }
        if (mSelectedIndex == 0) {
            liveRoomFragment.onRefresh();
        } else if (mSelectedIndex == 1) {
            chatRoomFragment.onRefresh();
        }
    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
//        JLog.e("event=" + motionEvent + "\ncontainer=" + container + "\n" + fragmentChangeHelper);
        if (container == null) {
            return false;
        }
//        JLog.e("ssd  " + verOffset + "   " + r);
        if (verOffset > 0) {
            return true;
        }
        if (ViewUtils.isTouchPointInView(container, motionEvent.getRawX(), motionEvent.getRawY(), 0)
                && fragmentChangeHelper != null) {
            if (fragmentChangeHelper.getShowingFragment() != null) {
                return fragmentChangeHelper.getShowingFragment().canScrollUp(motionEvent);
            }
        }
        return false;
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        if (container == null) {
            return false;
        }
        if (ViewUtils.isTouchPointInView(container, motionEvent.getRawX(), motionEvent.getRawY(), 0)
                && fragmentChangeHelper != null) {
            if (fragmentChangeHelper.getShowingFragment() != null) {
                return fragmentChangeHelper.getShowingFragment().canScrollDown(motionEvent);
            }
        }
        return false;
    }

    @Override
    protected void onChangeToPlaying() {
        openBarrage();
    }

    @Override
    protected void onChangeToStop() {
        closeBarrage();
    }

    @Override
    public void openOrCloseBarrage(boolean isOpen) {
        if (isOpen) {
            openBarrage();
        } else {
            closeBarrage();
        }
    }

    @Override
    public void onNetPrepare(LivingChildFragment fragment, int mode) {
        if (fragment == chatRoomFragment) {
            if (mode == ChatRoomFragment.MODE_COMMENT) {
                if (mFLive != null) {
                    showCommentDialog(mFLive.getLiveInfo().getLiveId(),mFLive.getLiveInfo().getLiveTitle(), null, Constances.COMMENT_TYPE_LIVE);
                }
            }
        } else if (fragment == liveRoomFragment) {
            if (mode == LivingChildFragment.MODE_PLAY) {
                if (isPlayFromRoom && floatVideoUtils != null && roomPlayedPos > 0) {
                    floatVideoUtils.startPlay();
                }
            }
        }
    }

    @Override
    public void onNetEnd(LivingChildFragment fragment, int mode, boolean canLoadMore) {
        if (mode == LivingChildFragment.MODE_PLAY) {
            if (fragment == liveRoomFragment) {
                if (isPlayFromRoom && floatVideoUtils != null && floatVideoUtils.isPlaying()) {
                    roomPlayedPos = 1;
                    floatVideoUtils.stopVideoView(false);
                } else {
                    roomPlayedPos = 0;
                }
            }
        } else {
            onNetFinish(canLoadMore);
        }
    }

    @Override
    public void doOther(LivingChildFragment fragment, int mode, Object obj, Object obj2) {
        if (fragment == liveRoomFragment) {
            if (mode == LivingChildFragment.MODE_PLAY) {
                if (obj instanceof FLiveDy) {
                    FLiveDy fld = (FLiveDy) obj;
                    if (fld == null || TextUtils.isEmpty(fld.getDyVideoUrl())) {
                        toast(R.string.data_wrong);
                    } else {
//                        playVideo((View) obj2, , false, true);s
                        otherVideoTemp = fld;
                        SkipUtil.skipToVideoPlay(this, UrlUtils.linkUrls(Constances.ST_BASE_URL, fld.getDyVideoUrl()), fld.getPlayedPos(), 0);
                    }
                }
            }
        }
    }

//    @Override
//    protected boolean isShouldMuteStart() {
//        return !isPlayFromRoom && isFirstPlay && NetModeUtil.GetNetype(this) == 1;
//    }

    @Override
    public void onRecylerScroll(int dx, int dy) {
        if (isPlayFromRoom && floatVideoUtils != null) {
//            floatVideoUtils.scrollBy(dx, dy);
            floatVideoUtils.recyclerScrolled(dx, dy);
        }
    }

    @OnCheckedChanged(R.id.living_sec_toggle)
    public void toggleChange(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            layIntro.setVisibility(View.VISIBLE);
            introToggle.setText(R.string.collapse_intro);
        } else {
            layIntro.setVisibility(View.GONE);
            introToggle.setText(R.string.expande_intro);
        }
        if (isPlayFromRoom) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (isPlayFromRoom) {
                        ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) videoContainer.getLayoutParams();
//                        mlp.topMargin = linear.getHeight() - container.getHeight() + layTitle.getHeight();
                        mlp.height = container.getHeight();
                        videoContainer.setLayoutParams(mlp);
                    }
                }
            }, 100);
        }
    }

    @OnClick({R.id.living_tab_room_living, R.id.living_tab_room_chat})
    public synchronized void tabClick(View view) {
//        handler.sendEmptyMessageDelayed(1,500);
//        if (mIsLoading) {
//            return;
//        }
//        clickTemp = false;
        int id = view.getId();
        if (id == R.id.living_tab_room_living) {
            selectTab(tabLive, tabChat);
            if (liveRoomFragment == null) {
                liveRoomFragment = new LiveRoomFragment();
                liveRoomFragment.setBaseUrl(mUrl);
                if (mFLive != null && mFLive.getLiveInfo() != null) {
//                    clickTemp = liveRoomFragment.setLiveInfo(mFLive.getLiveInfo());
//                    liveRoomFragment.setDatas(mFLive.getChannel(), LivingChildFragment.MODE_NORMAL);
                    liveRoomFragment.setLiving(mFLive.getLiveInfo().isLiving());
                    liveRoomFragment.setBaseLiveId(mFLive.getLiveInfo().getLiveId());
                }
            }
            fragmentChangeHelper.showFragment(liveRoomFragment, getSupportFragmentManager(), 0);
            mSelectedIndex = 0;
        } else if (id == R.id.living_tab_room_chat) {
            selectTab(tabChat, tabLive);
            if (chatRoomFragment == null) {
                chatRoomFragment = new ChatRoomFragment();
                if (mFLive != null && mFLive.getLiveInfo() != null) {
                    chatRoomFragment.setLiving(mFLive.getLiveInfo().isLiving());
                    chatRoomFragment.setBaseLiveId(mFLive.getLiveInfo().getLiveId());
                }
            }
            fragmentChangeHelper.showFragment(chatRoomFragment, getSupportFragmentManager(), 1);
            mSelectedIndex = 1;
            if (floatVideoUtils != null && isPlayFromRoom) {
                floatVideoUtils.stopVideoView(false);
            }
        }

        checkCanLoadMore();
    }

    private void checkCanLoadMore() {
        if (mSelectedIndex == 0) {
            mRefreshLayout.setLoadMoreEnabled(liveRoomFragment.canLoadMore());
        } else if (mSelectedIndex == 1) {
            mRefreshLayout.setLoadMoreEnabled(chatRoomFragment.canLoadMore());
        }
    }

    @OnClick(R.id.living_img_play)
    public void click(View view) {
        if (mFLive == null || TextUtils.isEmpty(mFLive.getLiveInfo().getLiveUrl())) {
            toast("数据错误");
            return;
        }
        playVideo(topImg, mFLive.getLiveInfo().getLiveUrl(), mFLive.getLiveInfo().isLiving(), false);
    }

    private void openBarrage() {
        if (barrageTestAsync != null) {
            barrageTestAsync.stop();
        }
        barrageTestAsync = new BarrageTestAsync();
        barrageTestAsync.ex();
    }

    private void closeBarrage() {
        if (barrageTestAsync != null) {
            barrageTestAsync.stop();
        }
    }

    private void playVideo(final View refer, final String url, final boolean isLiving, final boolean isFromRoom) {
//        AbsoluteLayout container = videoContainer;
//        if (isFromRoom) {
//            isLiving = false;
//            container = videoRoomContainer;
//        }
        if (initFloatVideoUtils(refer, videoContainer, 0)) {
//            bottomController.initInfo(liveInfo);
            floatVideoUtils.showPlayer(refer, false);
        } else {
            floatVideoUtils.stopVideoView(false);
        }
        if (videoPlayer != null && videoPlayer.getThumbImge() != null) {
            GlideUtil.getGlideWithLarge169DefNotFit(this, topImgUrl).into(videoPlayer.getThumbImge());
        }
        ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) videoContainer.getLayoutParams();
        int oh = 0;
        if (isFromRoom) {
//            mlp.topMargin = topImg.getHeight() + layTitle.getHeight() - verOffset;
            oh = linear.getHeight() - container.getHeight() + layTitle.getHeight();
            mlp.height = container.getHeight();
//            JLog.e("will set height  "+ mlp.height);
        } else {
            roomPlayedPos = 0;
            mlp.height = ViewGroup.LayoutParams.MATCH_PARENT;
        }
        floatVideoUtils.setOtherHeight(oh);
        videoContainer.setLayoutParams(mlp);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                floatVideoUtils.setLiving(isLiving);
                floatVideoUtils.showPlayer(refer, false);
                String str = "";
                if (mFLive != null && mFLive.getLiveInfo() != null) {
                    str = mFLive.getLiveInfo().getLiveTitle();
                }
//                videoPlayer.setUp(url, false, str);
//                videoPlayer.startPlay();
                if (videoPlayer != null && isShouldMuteStart()) {
                    videoPlayer.setMute(true);
                } else {
                    if (isFromRoom) {
                        if (videoPlayer.isMute()) {
                            videoPlayer.setMute(false);
                        }
                    }
                }
                floatVideoUtils.play(refer, url, str, true);
                if (videoPlayer != null) {
                    videoPlayer.setShowLiveMode(isLiving);
                }
                isFirstPlay = false;
            }
        }, 80);
        isPlayFromRoom = isFromRoom;

    }

    private void freshVideoContain(int h) {
        ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) videoContainer.getLayoutParams();
        mlp.topMargin = topImg.getHeight() + layTitle.getHeight() + h;
        videoContainer.setLayoutParams(mlp);
    }

    private void msgHandler(Message msg) {
        if (msg.what == 1) {
//            JLog.e("scroll h="+scrollView.getHeight()+"\nimg    h="+img.getHeight()
//                    +"\nrecycl h="+recyclerView.getHeight());
//            appBarLayout.invalidate();
        }
    }

    private void selectTab(CustomFontTextView select, CustomFontTextView another) {
        hasSelectRoom = true;
        Drawable d = ContextCompat.getDrawable(this, R.drawable.icon_bottom_line);
//        select.getCompoundDrawablePadding();
        d.setBounds(0, 0, select.getWidth(), DensityUtil.dip2px(this, 1));
        select.setCompoundDrawables(null, null, null, d);
        another.setCompoundDrawables(null, null, null, null);
        select.setTextColor(ContextCompat.getColor(this, R.color.colorRedf2));
        another.setTextColor(ContextCompat.getColor(this, R.color.colorBlack));
    }

    private void getData() {
        NetUtils.getNetAdapter().getLiveInfo(getOwnerName(), mUrl, new AbsNetCallBack<FLive>(FLive.class) {
            @Override
            public void onSuc(FLive fLive) {
                if (fLive == null || fLive.getLiveInfo() == null) {
                    onError(null, null);
                    return;
                }
                FLive live = mFLive;
                if (initInfo(fLive)) {
                    boolean should = true;
                    if (live != null) {
                        if (live.getLiveInfo() != null) {
                            if (!TextUtils.equals(live.getLiveInfo().getLiveId(), fLive.getLiveInfo().getLiveId())) {
                                deltJpushTag(live.getLiveInfo().getLiveId());
                            } else {
                                should = false;
                            }
                        }
                    }
                    if (UserManager.isLoginS()) {
                        StatisticsMainInit.newsInfoVisit(UserManager.getInstance().getUser().getPhoneNumber(), mFLive.getLiveInfo().getLiveId(),
                                mFLive.getLiveInfo().getLiveTitle(), "","0");
                    } else {
                        StatisticsMainInit.newsInfoVisit("", mFLive.getLiveInfo().getLiveId(),
                                mFLive.getLiveInfo().getLiveTitle(), "","0");
                    }
                    if (should) {
                        setJPushTag(fLive.getLiveInfo().getLiveId());
                    }
                    if (fragmentChangeHelper != null && fragmentChangeHelper.getShowingFragment() != null) {
                        fragmentChangeHelper.getShowingFragment().setBaseLiveId(fLive.getLiveInfo().getLiveId());
                        fragmentChangeHelper.getShowingFragment().setLiving(fLive.getLiveInfo().isLiving());
                        fragmentChangeHelper.getShowingFragment().onRefresh();
                    } else {
                        tabClick(tabLive);
                    }
                }
                getLiveCount(fLive.getLiveInfo().getLiveId());
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(R.string.loading_no_data);
            }

            @Override
            public void onEnd() {
                onNetFinish(false);
            }
        });
    }


    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (isFirst) {
                isFirst = false;
                if (UserManager.isLoginS()) {
                    StatisticsMainInit.livePlay(UserManager.getInstance().getUser().getPhoneNumber(), mFLive.getLiveInfo().getLiveId(),
                            mFLive.getLiveInfo().getLiveTitle(), 60);
                } else {
                    StatisticsMainInit.livePlay("", mFLive.getLiveInfo().getLiveId(),
                            mFLive.getLiveInfo().getLiveTitle(), 60);
                }
                handler.postDelayed(this, 60000);
            } else {
                if (UserManager.isLoginS()) {
                    StatisticsMainInit.livePlay(UserManager.getInstance().getUser().getPhoneNumber(), mFLive.getLiveInfo().getLiveId(),
                            mFLive.getLiveInfo().getLiveTitle(), 60);
                } else {
                    StatisticsMainInit.livePlay("", mFLive.getLiveInfo().getLiveId(),
                            mFLive.getLiveInfo().getLiveTitle(), 60);
                }
                handler.postDelayed(this, 60000);
            }


        }
    };


    private void getLiveCount(String newsId) {
        ArrayMap<String, Object> p = new ArrayMap<>();
        p.put("id", newsId);
        p.put("type", 1); //type（0.新闻 1.直播)
        p.put("category", 0);//category（栏目类型)
        NetUtils.getNetAdapter().getNewOrLivingClick(getOwnerName(), p, new AbsNetCallBack<NewsClickBean>(NewsClickBean.class) {
            @Override
            public void onSuc(NewsClickBean bean) {
                JLog.e("NewsClickBean", bean.getViews() + "");
//                String format = UIUtils.formatNumber(bean.getViews());
//                if (!TextUtils.isEmpty(format)) {
//                    mLiveCountText.setText(format);
//                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                JLog.e("getLiveCount", errorMsg);
            }
        });
    }

    private void deltJpushTag(String tag) {
        if (TextUtils.isEmpty(tag)) {
            return;
        }
        JLog.e("MyJPushReceiver    will del tag::" + tag);
        HashSet<String> set = new HashSet<>();
        set.add(tag);
        JPushInterface.deleteTags(this, 1, set);
    }

    private void setJPushTag(String tag) {
        if (TextUtils.isEmpty(tag)) {
            return;
        }
        JLog.e("MyJPushReceiver    set tag::" + tag);
        HashSet<String> set = new HashSet<>();
        set.add(tag);
        JPushInterface.addTags(this, 1, set);
    }

    private Gson getGson() {
        if (gson == null) {
            gson = new Gson();
        }
        return gson;
    }

    private boolean isFirstInitInfo = true;

    private boolean initInfo(FLive fLive) {
        mFLive = fLive;
        if (fLive.getLiveInfo() != null) {
            startAdService(handler1);
            RHLogger.getInstance().startLive(mFLive.getLiveInfo().getLiveId());
            liveSource.setText(MessageFormat.format("直播来源:{0}", mFLive.getLiveInfo().getLiveSource()));
            intro.setText(MessageFormat.format("简介：{0}", mFLive.getLiveInfo().getLiveIntro()));
            date.setText(DateUtils.getDateDayString(DateUtils.getDataDate(mFLive.getLiveInfo())));
            handler.sendEmptyMessageDelayed(1, 300);
            livtTag.setVisibility(mFLive.getLiveInfo().isLiving() ? View.VISIBLE : View.GONE);
            liveUrl = mFLive.getLiveInfo().getLiveUrl();
            if (NetUtils.isWifiConnected(this)) {
                click(null);
            }
//            if (isFirstInitInfo){
//                isFirstInitInfo=false;
//                introToggle.setChecked(true);
//            }
            initViewClickData(fLive.getLiveInfo().getLiveId());
            return true;
        }
        return false;

//        if (mSelectedIndex == 0) {
//            liveRoomFragment.getData();
//        } else if (mSelectedIndex == 1) {
//            chatRoomFragment.getData();
//        }
    }

    @Override
    public void onClick(String imageUrl) {

    }

    @Override
    public void onMsgRecieve(Context context, Intent intent, JSONObject object, boolean isDynam) {
        if (object == null) {
            return;
        }
        try {
            if (isDynam) {
                object = object.getJSONObject("data");
                if (object == null) {
                    return;
                }
                FLiveDy dynamic = getGson().fromJson(object.toString(), FLiveDy.class);
                if (liveRoomFragment != null) {
                    liveRoomFragment.addData(dynamic, 0);
                }
            } else {
                JSONArray ja = object.getJSONArray("data");
                if (ja == null || ja.length() == 0) {
                    return;
                }
                List<ChatItem> list = getGson().fromJson(ja.toString(), ListTypeUtils.ChatItem());
                if (chatRoomFragment != null && ListUtils.isListValued(list)) {
                    new ResultAsyncTask<Void>(list) {
                        @Override
                        protected Void doInBackground(Void... params) {
                            Collections.sort((List<ChatItem>) obj, new Comparator<ChatItem>() {
                                @Override
                                public int compare(ChatItem o1, ChatItem o2) {
                                    if (o1 != null && o2 != null) {
                                        Date date = DateUtils.getDataDate(o2);
                                        Date date1 = DateUtils.getDataDate(o1);
                                        int i = date.compareTo(date1);
                                        return i;
                                    }
                                    return 0;
                                }
                            });
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            if (chatRoomFragment != null) {
                                chatRoomFragment.addDatas((List<ChatItem>) obj, 0);
                            }
                        }
                    }.execute();

                }
                //shouldsetbarrage
                if (screenController != null && floatVideoUtils != null && floatVideoUtils.isPlaying()
                        && screenController.canBarrage() && ListUtils.isListValued(list)) {
                    for (int i = 0; i < list.size(); i++) {
                        String str = list.get(i).getChatContent();
                        JLog.e("will send barrage  " + str + "   " + list.get(i));
                        if (!TextUtils.isEmpty(str)) {
                            screenController.addMsg(str);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private class BarrageTestAsync extends ResultAsyncTask<Void> {
        private boolean canRun = true;

        @Override
        protected Void doInBackground(Void... params) {
            String[] strs = getResources().getStringArray(R.array.titlesss);
            while (canRun) {
                if (screenController != null) {
//					screenController.addMsg(strs[(int) (Math.random() * strs.length)]);
                }
                try {
                    Thread.sleep((long) (Math.random() * 10000L + 50));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        public void stop() {
            canRun = false;
        }
    }

    public boolean isLoading() {
        return mIsLoading;
    }

    public String getCompere() {
        return mFLive.getLiveInfo().getLiveCompere();
    }

//    public String getChildUrl(int index) {
//        return mFLive == null || !ListUtils.isListValued(mFLive.getChannel()) ? "" : mFLive.getChannel().get(index).getChannelUrl();
//    }

    public void onNetFinish(boolean loadMoreEnabled) {
        mIsLoading = false;
        mRefreshLayout.refreshComplete();
        mRefreshLayout.loadMoreComplete();
        mRefreshLayout.setLoadMoreEnabled(loadMoreEnabled);
        MyJPushReceiver.setMsgRecieve(this);
    }
}
